﻿using AutoMapper;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using ShenNius.Cms.API.Domain.Entity;
using ShenNius.Cms.API.Dtos.Input;
using ShenNius.Cms.API.Dtos.Output;
using ShenNius.Repository;
using ShenNius.Sys.API.Controllers;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Infrastructure.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

/*************************************
* 类名：KeywordController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/3/31 19:08:12
*┌───────────────────────────────────┐　    
*│　     版权所有：神牛软件　　　　	 │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Cms.API.Controllers
{
    [Route("api/cms/[controller]/[action]")]
    public class KeywordController : ApiTenantBaseController<Keyword, DetailTenantQuery, DeletesTenantInput, ListTenantQuery, KeywordInput, KeywordModifyInput>
    {
        private readonly IBaseRepository<Keyword> _repository;
        private readonly IMapper _mapper;

        public KeywordController(IBaseRepository<Keyword> repository, IMapper mapper) : base(repository, mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }
        /// <summary>
        /// 一键匹配内链，只替换第一个匹配到的字符
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ContentReplace([FromBody] ContentHrefInput input)
        {
            if (input.Type == "edit")
            {
                input.Content = WebHelper.ReplaceStrHref(input.Content);
            }
            var list = await _repository.GetListAsync();
            if (list == null || list.Count == 0)
            {
                throw new ArgumentNullException("关键字库中没有数据,检查集合是否抛异常了");
            }

            int n = -1;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < list.Count; i++)
            {
                if (Regex.Match(input.Content, list[i].Title).Success)
                {
                    string pattern = $"<a href=\"{list[i].Url}\" target=\"_blank\">{list[i].Title}</a>";
                    // 第一次
                    Regex reg = new Regex(list[i].Title);
                    input.Content = reg.Replace(input.Content, pattern, 1);
                    if (Regex.Match(input.Content, pattern).Success)
                    {
                        //如果当前关键字链接信息成功，将当前的文本链接信息提取出来添加到字典中（dic）,并以唯一标识符代替文本链接信息作为占位符。
                        reg = new Regex(pattern);
                        n++;
                        input.Content = reg.Replace(input.Content, "{" + n + "}", 1);
                        dic.Add("{" + n + "}", pattern);
                    }
                }
            }
            //将匹配到的文本链接信息format
            if (dic.Count != 0)
            {
                int m = -1;
                foreach (string key in dic.Keys)
                {
                    m++;
                    if (input.Content.Contains("{" + m + "}"))
                    {
                        input.Content = input.Content.Replace("{" + m + "}", dic[key]);
                    }
                }
            }
            input.Content = WebHelper.RemoveStrImgAlt(input.Content);
            return new ApiResult(data: input.Content);
        }
        [HttpGet]
        public override async Task<IActionResult> GenerateImportTemplate()
        {
            var fileName = await NPOIHelper.GenerateImportTemplate<ImportKeywordInput>();
            return File(System.IO.File.ReadAllBytes(fileName), "application/vnd.ms-excel", $"{nameof(ImportKeywordInput)}.xlsx");
        }
        [HttpPost]
        public override async Task<ApiResult> Import()
        {
            var file = Request.Form.Files[0];
            var list = await NPOIHelper.Import<ImportKeywordInput>(file);
            if (list != null && list.Count > 0)
            {
                var keywords = new List<Keyword>();
                foreach (var item in list)
                {
                    keywords.Add(Keyword.Create(item.Title, item.Url));
                }
                if (keywords.Count > 0)
                {
                    await _repository.AddListAsync(keywords);
                }
                return ApiResult.Successed($"{list.Count}条数据已成功导入！");
            }
            return new ApiResult("没有数据导入");
        }
        [HttpGet]
        public override async Task<IActionResult> Export([FromQuery] ListTenantQuery listQuery)
        {
            List<Keyword> keywords = new List<Keyword>();
            if (listQuery != null)
            {
                var res = await _repository.GetPagesAsync(listQuery.Page, listQuery.Limit, d => d.IsDeleted == false && d.TenantId == listQuery.TenantId, d => d.Id, false);
                if (res != null&&res.TotalItems>0)
                {
                    keywords=res.Items;
                }
            }
            else {
                keywords = await _repository.GetListAsync(d => !d.IsDeleted);
            }            
            if (keywords.Count <= 0)
            {
                throw new ArgumentNullException("关键词列表没有可用数据导出！");
            }
            var datas = _mapper.Map<List<KeywordOutput>>(keywords);
            IExporter exporter = new ExcelExporter();
            var result = await exporter.Export($"{nameof(KeywordOutput)}.xlsx", datas);
            return File(System.IO.File.ReadAllBytes(result.FileName), "application/vnd.ms-excel", $"{nameof(KeywordOutput)}.xlsx");
        }
    }
}